package com.hyt.it.ogt.kq.service.gov.model.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.fastjson.JSON;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.service.gov.model.excel.BreakRuleBehaviorSheet;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author 刘恒活
 * @since 2021/8/24 14:22
 */
@Slf4j
public class BreakRuleBehaviorListener extends AbstractAnalysisListener<BreakRuleBehaviorSheet> {
    private final List<BreakRuleBehaviorSheet> list = new ArrayList<>();
    private static final List<String> STANDARD_HEAD_MAP = Arrays.asList("违纪处理代码", "违纪处理办法", "停考年限");

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("违纪行为表解析到一条头数据:{}", JSON.toJSONString(headMap));
        super.checkHeadField(headMap, STANDARD_HEAD_MAP, log);
    }

    @Override
    public void invoke(BreakRuleBehaviorSheet data, AnalysisContext context) {
        log.info("违纪行为表解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("违纪行为表解析失败，但是继续解析下一行:{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("违纪行为表第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            throw new ExcelAnalysisStopException(exception.getMessage());
        }
        if (exception instanceof KqException) {
            throw new ExcelAnalysisStopException(exception.getMessage());
        }
    }

    public List<BreakRuleBehaviorSheet> getData() {
        return list;
    }

}
